package com.lhz.framework.security.manager.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.lhz.common.constant.TokenConstant;
import com.lhz.framework.security.manager.SecurityManager;
import com.lhz.framework.security.manager.TokenManager;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author lihuazhi
 */
@Component
public class RedisSecurityManager<T> implements SecurityManager<T> {
    /**
     * token管理器
     */
    @Resource
    private TokenManager tokenManager;


    @Override
    public T getUserInfo(String tokenKey) {
        if (StrUtil.isEmpty(tokenKey)) {
            return null;
        }
        return (T) tokenManager.getUserInfoByToken(tokenKey);
    }

    @Override
    public void removeUser(String tokenKey) {
        if (tokenManager.hasKey(tokenKey)) {
            tokenManager.removeUserToken(tokenKey);
        }
    }

    /**
     * 刷新用户登录过期时间
     *
     * @param tokenKey
     */
    @Override
    public void refreshExpiry(String tokenKey) {
        // 游客无需刷新
        if (TokenConstant.VISITOR_TOKEN.equals(tokenKey)) {
            return;
        }
        tokenManager.refreshExpire(tokenKey);
    }

    /**
     * 检查token是否存在
     *
     * @param tokenKey
     * @return
     */
    @Override
    public boolean checkToken(String tokenKey) {
        // 游客无需判断
        if (TokenConstant.VISITOR_TOKEN.equals(tokenKey)) {
            return true;
        }
        return tokenManager.hasKey(tokenKey);
    }


    /**
     * 检查角色是否符合
     *
     * @param tokenKey
     * @param requireRole
     * @return
     */
    @Override
    public boolean checkRole(String tokenKey, String[] requireRole) {
        List<String> userRole = (List<String>) tokenManager.getUser(tokenKey, TokenConstant.USER_INFO_KEY);
        if (CollectionUtil.isEmpty(userRole)) {
            return false;
        }
        for (String r : requireRole) {
            for (String role : userRole) {
                if (r.equals(role)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 检查是否拥有权限
     *
     * @param tokenKey
     * @param requireRights
     * @return
     */
    @Override
    public boolean checkRights(String tokenKey, String[] requireRights) {
        List<String> userRights = (List<String>) tokenManager.getUser(tokenKey, TokenConstant.USER_INFO_KEY);
        if (CollectionUtil.isEmpty(userRights)) {
            return false;
        }
        for (String r : requireRights) {
            for (String p : userRights) {
                if (r.equals(p)) {
                    return true;
                }
            }
        }
        return false;
    }


}
